{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def describe(x):\n",
    "    print(\"Type: {}\".format(x.type()))\n",
    "    print(\"Shape/size: {}\".format(x.shape))\n",
    "    print(\"Values: \\n{}\".format(x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Type: torch.FloatTensor\n",
      "Shape/size: torch.Size([3, 4])\n",
      "Values: \n",
      "tensor([[1., 2., 3., 4.],\n",
      "        [5., 6., 7., 0.],\n",
      "        [8., 0., 0., 0.]])\n"
     ]
    }
   ],
   "source": [
    "abcd_padded = torch.tensor([1, 2, 3, 4], dtype=torch.float32)\n",
    "efg_padded = torch.tensor([5, 6, 7, 0], dtype=torch.float32)\n",
    "h_padded = torch.tensor([8, 0, 0, 0], dtype=torch.float32)\n",
    "\n",
    "padded_tensor = torch.stack([abcd_padded, efg_padded, h_padded])\n",
    "\n",
    "describe(padded_tensor)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PackedSequence(data=tensor([1., 5., 8., 2., 6., 3., 7., 4.]), batch_sizes=tensor([3, 2, 2, 1]))"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lengths = [4, 3, 1]\n",
    "packed_tensor = pack_padded_sequence(padded_tensor, lengths, \n",
    "                                     batch_first=True)\n",
    "packed_tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Type: torch.FloatTensor\n",
      "Shape/size: torch.Size([3, 4])\n",
      "Values: \n",
      "tensor([[1., 2., 3., 4.],\n",
      "        [5., 6., 7., 0.],\n",
      "        [8., 0., 0., 0.]])\n",
      "Type: torch.LongTensor\n",
      "Shape/size: torch.Size([3])\n",
      "Values: \n",
      "tensor([4, 3, 1])\n"
     ]
    }
   ],
   "source": [
    "unpacked_tensor, unpacked_lengths = pad_packed_sequence(packed_tensor, batch_first=True)\n",
    "describe(unpacked_tensor)\n",
    "describe(unpacked_lengths)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "nlpbook",
   "language": "python",
   "name": "nlpbook"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
